package com.yunlinker.asba.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.MimeTypeMap;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alipay.sdk.app.PayTask;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.LogUtils;
import com.qiyukf.unicorn.api.ConsultSource;
import com.qiyukf.unicorn.api.OnMessageItemClickListener;
import com.qiyukf.unicorn.api.ProductDetail;
import com.qiyukf.unicorn.api.Unicorn;
import com.qiyukf.unicorn.api.UnreadCountChangeListener;
import com.qiyukf.unicorn.api.YSFUserInfo;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengCallback;
import com.umeng.message.PushAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yunlinker.asba.Constant;
import com.yunlinker.asba.MainApplication;
import com.yunlinker.asba.PayResult;
import com.yunlinker.asba.R;
import com.yunlinker.asba.WLWebView.WLWebView;
import com.yunlinker.asba.aliupload.ImageService;
import com.yunlinker.asba.aliupload.OssService;
import com.yunlinker.asba.aliupload.PauseableUploadTask;
import com.yunlinker.asba.aliupload.STSGetter;
import com.yunlinker.asba.bean.URL;
import com.yunlinker.asba.db.DatabaseUtil;
import com.yunlinker.asba.helper.MyActivityManager;
import com.yunlinker.asba.helper.MySharePreferenceHelper;
import com.yunlinker.asba.helper.SDcardHelper;
import com.yunlinker.asba.imp.QiyuUrlOnclickerimp;
import com.yunlinker.asba.model.DeviceModel;
import com.yunlinker.asba.model.LoadBase64Img;
import com.yunlinker.asba.model.LocationModel;
import com.yunlinker.asba.model.SaveImg;
import com.yunlinker.asba.model.ScanfModel;
import com.yunlinker.asba.networkcallback.PublicMyStringCallBack;
import com.yunlinker.asba.utils.DemoCache;
import com.yunlinker.asba.utils.FileUtils;
import com.yunlinker.asba.utils.GetImei;
import com.yunlinker.asba.utils.GsonUtils;
import com.yunlinker.asba.utils.ImageFilePath;
import com.yunlinker.asba.utils.LogUtills;
import com.yunlinker.asba.utils.PhotoChoose;
import com.yunlinker.asba.utils.ToastUtil;
import com.yunlinker.asba.utils.Utils;
import com.zfdang.multiple_images_selector.ImagesSelectorActivity;
import com.zfdang.multiple_images_selector.SelectorSettings;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity implements UnreadCountChangeListener ,QiyuUrlOnclickerimp {


    WLWebView webview;


    /**
     * 加载的链接地址
     */
    String loadUrl = "";

    /**
     * 需要上传到服务器的地址
     */
    String upLoadImgUrl = "";


    /**
     * 这里是上传图片到阿里云服务器的相关属性
     */
    private OssService ossService;
    private ImageService imageService;
    private static final String bucket = "asba-upload";
    private static final String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
    private WeakReference<PauseableUploadTask> task;
    private Handler mPayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResults = new PayResult((String) msg.obj);
            JSONObject jb = new JSONObject();
            switch (msg.what) {
                case 1: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        try {
                            jb.put("code", 1);
                            jb.put("msg", "");
                        } catch (Exception e) {
                        }
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        try {
                            jb.put("code", 0);
                            jb.put("msg", "支付失败");
                        } catch (Exception e) {
                        }
                    }
                    break;
                }
                default:
                    break;
            }
            setValue("pay", jb.toString());
        }
    };

    public static void invokeActivity(Context context, String url) {

        Intent it = new Intent(context, MainActivity.class);
        it.putExtra("sendUrl", url);
        context.startActivity(it);
        try {
            LogUtills.LogShow("invokeActivity", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
//        parseIntent();
    }

    /**
     * 数据库保存图片到本地
     */
    DatabaseUtil databaseUtil;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MainApplication.activiedActicity++;
        if (getIntent().getFlags() ==872415232) {
            MySharePreferenceHelper.setString("__firstLaunch", "1");
            MySharePreferenceHelper.setString("qiyu", "{}");
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Translucent status bar
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (MIUISetStatusBarLightMode(this.getWindow(), true)) {//MIUI
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0
                    this.getWindow().setStatusBarColor(Color.WHITE);
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4
                    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                            WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    SystemBarTintManager tintManager = new SystemBarTintManager(this);
                    tintManager.setStatusBarTintEnabled(true);
                    tintManager.setStatusBarTintResource(android.R.color.white);
                }
            } else if (FlymeSetStatusBarLightMode(this.getWindow(), true)) {//Flyme
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0
                    this.getWindow().setStatusBarColor(Color.WHITE);
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4
                    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                            WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    SystemBarTintManager tintManager = new SystemBarTintManager(this);
                    tintManager.setStatusBarTintEnabled(true);
                    tintManager.setStatusBarTintResource(android.R.color.white);
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0
                this.getWindow().setStatusBarColor(Color.WHITE);
                this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }else{
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
             /*   View decorView = getWindow().getDecorView();
                //重点：SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                decorView.setSystemUiVisibility(option);
                getWindow().setStatusBarColor(Color.TRANSPARENT);*/
            }
        }
        setContentView(R.layout.activity_main);
        loadUrl = getIntent().getStringExtra("sendUrl");
        MyActivityManager.getScreenManager().pushActivity(this, loadUrl);
        unBind();

        //注册广播
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    private boolean isResume = false;

    @Override
    protected void onResume() {
        try {
            super.onResume();
            MobclickAgent.onResume(this);
            if (isResume) {
                try {
                    webview.post(new Runnable() {
                        @Override
                        public void run() {
                            webview.loadUrl("javascript:_w9_resume()");
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (MainApplication.getInstance().isRefreshHome) {
                MainApplication.getInstance().isRefreshHome = false;
                loadUrl = MainApplication.getInstance().isRefreshUrl;
                unBind();
            }

            //注册广播
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            openWebActivity = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    //添加应用前台客服消息监听
    private void addUnreadCountChangeListener(boolean add) {
        Unicorn.addUnreadCountChangeListener(this, add);
    }

    @Override
    protected void onPause() {
        try {
            super.onPause();
            MobclickAgent.onPause(this);
            isResume = true;
            if (openWebActivity && EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();

    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = true;
        //判断应用是否在前台
        if (Utils.isBackground(this)) {
            //后台
            LogUtills.LogShow("程序", "后台");
            Unicorn.toggleNotification(true);
        } else {
            //
            LogUtills.LogShow("程序", "前台");
            Unicorn.toggleNotification(false);
        }
        if(progressDialog!=null)
            progressDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        if (webview != null) {
            try {
                if (webview.getParent() != null) {
                    ((ViewGroup) webview.getParent()).removeView(webview);
                }
                webview.destroy();
            } catch (IllegalArgumentException e) {
            }
            webview = null;
        }
        super.onDestroy();

        MainApplication.activiedActicity--;

        cancelAllTasks();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }


    @Override
    public void onBackPressed() {
        setValue("back", "ANDROID_000000");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    /**
     * 获取需要打开的url链接,初始化webview
     */


    private void unBind() {
        initWebView();
        LogUtills.LogShow("loadUrl", loadUrl);
        if (!TextUtils.isEmpty(loadUrl)) {
//            webview.loadUrl(loadUrl.indexOf("http:")>-1?loadUrl:("file:///android_asset/www/"+loadUrl));
            webview.loadUrl(loadUrl.indexOf(URL.HTTP_HTTPS) > -1 ? loadUrl : (URL.DOMIAN + loadUrl));
        } else {//首页
//            webview.loadUrl("file:///android_asset/www/index.html");
            webview.loadUrl(URL.DOMIAN);
        }
    }

    @JavascriptInterface
    public void pay(String s) {
        try {
            String uuArray[] = getDataUUID(s);
            JSONObject jb = new JSONObject(uuArray[0]);
            MainApplication.userTimeSpan = jb.getString("_token");
            if (jb.getInt("type") == 1) {
                //支付宝
                getAliPayConfig(jb.getString("orderid"),uuArray[1]);
            } else if (jb.getInt("type") == 2) {
                //微信支付
                getWeChatPayConfig(jb.getString("orderid"),uuArray[1]);
            }
        } catch (Exception e) {
        }
    }

    // 获取支付宝支付签名
    private void getAliPayConfig(String orderIds,String uuidStr) {
        String stsJson;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(Constant.getAliPayConfigs + orderIds +
                "&_token=" + MainApplication.userTimeSpan).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                stsJson = response.body().string();
                JSONObject jb = new JSONObject(stsJson);
                String a = jb.getString("data");
                aLiPayStart(a);
            } else {
                setValue("pay", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\", msg:\"支付失败\"}"),uuidStr));
                throw new IOException("Unexpected code " + response);
            }
        } catch (Exception e) {
            setValue("pay", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\", msg:\"支付失败\"}"),uuidStr));
            e.printStackTrace();
            Log.e("GetSTSTokenFail", e.toString());
        }
    }

    private void aLiPayStart(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(MainActivity.this);
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    // 获取微信支付签名
    private void getWeChatPayConfig(String orderIds,String uuidStr) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(Constant.getWeChatPayConfigs + orderIds +
                "&_token=" + MainApplication.userTimeSpan).build();
        try {
            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                String wechatPayStr = response.body().string();
                weChatPayStart(wechatPayStr);
            } else {
                setValue("pay", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\", msg:\"支付失败\"}"),uuidStr));
                throw new IOException("Unexpected code " + response);
            }
        } catch (Exception e) {
            setValue("pay", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\", msg:\"支付失败\"}"),uuidStr));
            e.printStackTrace();
            Log.e("GetSTSTokenFail", e.toString());
        }
    }

    //微信开始支付
    private void weChatPayStart(String s) {
        try {
            JSONObject jb1 = new JSONObject(s);
            JSONObject jb = jb1.getJSONObject("data");
            String app_id = jb.getString("appid");
            MainApplication.APPID = app_id;
            IWXAPI iwxapi = WXAPIFactory.createWXAPI(MainActivity.this, app_id);
            iwxapi.registerApp(app_id);
            PayReq payRequest = new PayReq();
            payRequest.appId = app_id;
            payRequest.partnerId = jb.getString("partnerid");
            payRequest.prepayId = jb.getString("prepayid");
            payRequest.nonceStr = jb.getString("noncestr");
            payRequest.timeStamp = jb.getString("timestamp");
            payRequest.sign = jb.getString("sign");
            payRequest.packageValue = "Sign=WXPay";
            //发起请求
            iwxapi.sendReq(payRequest);
        } catch (Exception e) {
        }
    }

    /**
     * h5界面是否加载完成
     */
    private boolean isLoanFinished = false;
    /**
     * 初始化webView
     */
    private ValueCallback<Uri[]> mFilePathCallback;

    private void initWebView() {
        webview = (WLWebView) findViewById(R.id.wlweb);

        webview.setHorizontalScrollBarEnabled(false);//水平不显示
        webview.setVerticalScrollBarEnabled(false); //垂直不显示
        webview.addJavascriptInterface(this, "WeiLai");
//        webview.setWebContentsDebuggingEnabled(true);


        WebSettings setting = webview.getSettings();
        setting.setJavaScriptEnabled(true);//支持js

        // 设置可以支持缩放
        setting.setSupportZoom(true);
// 设置出现缩放工具
        setting.setBuiltInZoomControls(true);
//扩大比例的缩放
        setting.setUseWideViewPort(true);
/*//自适应屏幕
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setLoadWithOverviewMode(true);*/

        setting.setDefaultTextEncodingName("utf-8");
        setting.setDomStorageEnabled(true);
        setting.setAllowFileAccess(true);
        setting.setAllowContentAccess(true);
        setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        setting.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setting.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);

        }
        webview.setWebChromeClient(mWebChromeClient);

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else {
                    view.loadUrl(url);
                    return true;
                }

            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                isLoanFinished =true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); // 接受网站证书
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                //above 6.0
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    currentUrl = request.getUrl().toString();
//                }
//                showLocalErrorPage();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                // below 6.0
                currentUrl = failingUrl;
                showLocalErrorPage();
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }
        });


        //---------------安卓键盘处理-----------------
        webview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                webview.getWindowVisibleDisplayFrame(r);
                final int visibleHeight = r.height();
                if (screenHeight == 0) {
                    screenHeight = visibleHeight;
                } else {
                    if (visibleHeight > 100 && screenHeight != visibleHeight) {
                        //有可能为打开键盘
                        webview.post(new Runnable() {
                            @Override
                            public void run() {
                                float ratio = (screenHeight - visibleHeight) / (float) screenHeight;
                                webview.loadUrl("javascript:window.keyBoardEvent&&keyBoardEvent(1," + ratio + ");");
                            }
                        });
                    } else {
                        //有可能为关闭键盘
                        webview.post(new Runnable() {
                            @Override
                            public void run() {
                                webview.loadUrl("javascript:window.keyBoardEvent&&keyBoardEvent(0);");
                            }
                        });
                    }
                }
            }
        });
    }

    private String currentUrl = null ;
    /**
     * 显示本地错误界面
     */
    private void showLocalErrorPage() {

        webview.loadUrl("file:///android_asset/error/offline.html?url=%@");
    }

    /**
     * 点击刷新重新加载
     */
    @JavascriptInterface
    public void weakRelaod() {

        if (!TextUtils.isEmpty(currentUrl)) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webview.loadUrl(currentUrl);
                }
            });
        }
    }

    private int screenHeight = 0;

    private String mCameraPhotoPath;

    private File createImageFile() {
        File file = new File(Environment.getExternalStorageDirectory() + "/", "tmp.png");
        mCameraPhotoPath = file.getAbsolutePath();
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static final int INPUT_FILE_REQUEST_CODE = 55;
    private static final int FILECHOOSER_RESULTCODE = 33;
    private ValueCallback<Uri> mUploadMessage;
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        // android 5.0 这里需要使用android5.0 sdk
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) return true;
            mFilePathCallback = filePathCallback;
            selectImage();
            return true;
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {

            if (mUploadMessage != null) return;
            mUploadMessage = uploadMsg;
            selectImage();
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }
    };

    public final boolean checkSDcard() {
        boolean flag = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (!flag) {
            ToastUtil.showTop("请插入手机存储卡再使用本功能");
        }
        return flag;
    }

    String compressPath = "";

    protected final void selectImage() {
        if (!checkSDcard())
            return;
        String[] selectPicTypeStr = {"相机", "图库"};
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setItems(selectPicTypeStr,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                switch (which) {
                                    // 相机拍摄
                                    case 0:
                                        openCarcme();
                                        break;
                                    // 手机相册
                                    case 1:
                                        chosePic();
                                        break;
                                    default:
                                        break;
                                }
                                compressPath = Environment
                                        .getExternalStorageDirectory()
                                        .getPath()
                                        + "/fuiou_wmp/temp";
                                new File(compressPath).mkdirs();
                                compressPath = compressPath + File.separator
                                        + "compress.jpg";
                            }
                        }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        if (mFilePathCallback != null) {
                            Uri[] uris = new Uri[1];
                            uris[0] = Uri.parse("");
                            mFilePathCallback.onReceiveValue(uris);
                            mFilePathCallback = null;
                        } else {
                            mUploadMessage.onReceiveValue(Uri.parse(""));
                            mUploadMessage = null;
                        }
                    }
                }).show();
    }

    String imagePaths;
    Uri cameraUri;

    /**
     * 打开照相机
     */
    private void openCarcme() {
        // 必须确保文件夹路径存在，否则拍照后无法完成回调
        File vFile = new File(imagePaths);
        if (!vFile.exists()) {
            File vDirPath = vFile.getParentFile();
            vDirPath.mkdirs();
        } else {
            if (vFile.exists()) {
                vFile.delete();
            }
        }
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(MainActivity.this, "com.yunlinker.asba.fileProvider", vFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            startActivity(intent);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imagePaths = Environment.getExternalStorageDirectory().getPath()
                    + "/fuiou_wmp/temp/"
                    + (System.currentTimeMillis() + ".jpg");
            cameraUri = Uri.fromFile(vFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
            startActivityForResult(intent, REQ_CAMERA);
        }

    }

    private static final int REQ_CAMERA = 1111;
    private static final int REQ_CHOOSE = 2222;

    /**
     * 拍照结束后
     */
    private void afterOpenCamera() {
        File f = new File(imagePaths);
        addImageGallery(f);
    }

    /**
     * 解决拍照后在相册中找不到的问题
     */
    private void addImageGallery(File file) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    /**
     * 本地相册选择图片
     */
    private void chosePic() {
        FileUtils.delFile(compressPath);
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
        String IMAGE_UNSPECIFIED = "image/*";
        innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        startActivityForResult(wrapperIntent, REQ_CHOOSE);
    }

    /**
     * 选择照片后结束
     *
     * @param data
     */
    private Uri afterChosePic(Intent data) {

        // 获取图片的路径：
        String[] proj = {MediaStore.Images.Media.DATA};
        // 好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
        if (cursor == null) {
            ToastUtil.showTop("上传的图片仅支持png或jpg格式");
            return null;
        }
        // 按我个人理解 这个是获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        // 最后根据索引值获取图片路径
        String path = cursor.getString(column_index);
        if (path != null && (path.endsWith(".png") || path.endsWith(".PNG") || path.endsWith(".jpg") || path.endsWith(".JPG"))) {
            File newFile = FileUtils.compressFile(path, compressPath);
            return Uri.fromFile(newFile);
        } else {
            ToastUtil.showTop("上传的图片仅支持png或jpg格式");
        }
        return null;
    }


    /**
     * js调用原生
     * //mess,消息内容，time停留时间(单位毫秒)
     */
    @JavascriptInterface
    public void message(String mess) {
        ToastUtil.showTop(getDataUUID(mess)[0]);
//        setValue("message","1");
    }


    /**
     * js调用原生
     * //弹出确认dialog，包含确定，取消按钮
     */
    @JavascriptInterface
    public void confirm(String mess) {
        showConfirm(mess);
    }


    /**
     * js调用原生
     * //弹出对话框架dialog，包含提示内容，确定按钮
     */
    @JavascriptInterface
    public void alert(String mess) {
        showAlert(mess);
    }


    /**
     * js调用原生
     * 切换横屏竖屏
     */
    @JavascriptInterface
    public void rotate(String bgs) {
        String uuidStr[] = getDataUUID(bgs);
        if ("1".equals(uuidStr[0])) {//竖屏
            setValue("rotate", getDataUUIDJson("1",uuidStr[1]));
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //强制为竖屏
        } else {
            setValue("rotate", getDataUUIDJson("2",uuidStr[1]));
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //强制为横屏
        }
    }


    /**
     * js调用原生
     * 背景色
     */
    @JavascriptInterface
    public void setbg(String bgs) {
        setValue("setbg", getDataUUIDJson("1",getDataUUID(bgs)[1]));
    }


    /**
     * js调用原生
     * 设备信息
     */
    @JavascriptInterface
    public void deviceInfo(String s) {
        String imei = GetImei.getImei(this);
        DeviceModel deviceModel = new DeviceModel();
        deviceModel.setType("android");
        deviceModel.setImei(imei);
        int currentapiVersion = Build.VERSION.SDK_INT;
        switch (currentapiVersion) {
            case 15:
                deviceModel.setVer("4.x");
                break;
            case 16:
                deviceModel.setVer("4.x");
                break;
            case 17:
                deviceModel.setVer("4.x");
                break;
            case 18:
                deviceModel.setVer("4.x");
                break;
            case 19:
                deviceModel.setVer("4.x");
                break;
            case 20:
                deviceModel.setVer("4.0");
                break;
            case 21:
                deviceModel.setVer("5.0");
                break;
            case 22:
                deviceModel.setVer("5.0");
                break;
            case 23:
                deviceModel.setVer("6.0");
                break;
            case 24:
                deviceModel.setVer("7.0");
                break;
            default:
                deviceModel.setVer("未知");
                break;
        }
        setValue("deviceInfo", getDataUUIDJson(singleDoubleQuotes(GsonUtils.getInstance().toJson(deviceModel)),getDataUUID(s)[1]));
    }

    @JavascriptInterface
    public void shareUrl(String s) {
        try {
            String dataUUIDArr[] = getDataUUID(s);
            JSONObject jb = new JSONObject(dataUUIDArr[0]);
            showShare(jb.getString("pic"), jb.getString("title"), jb.getString("desc"), jb.getString("url"),dataUUIDArr[1]);
        } catch (Exception e) {
        }

    }

    /**
     * 三方分享
     */
    private void showShare(String imgUrl, String title, String desc, String url,final String uuidStr) {
        UMImage image = new UMImage(MainActivity.this, imgUrl);
        UMWeb web = new UMWeb(url);
        web.setTitle(title);//标题
        web.setThumb(image);  //缩略图
        web.setDescription(desc);//描述
//        SHARE_MEDIA.SINA
        new ShareAction(MainActivity.this).withMedia(web)
                .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                        LogUtills.LogShow("分享", share_media.name());
                        if (share_media == SHARE_MEDIA.QQ || share_media == SHARE_MEDIA.QZONE) {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                                    && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                                    ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_STORAGE_CODE);
                            }
                        }
                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        setValue("shareUrl", getDataUUIDJson("1",uuidStr));
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        if(!UMShareAPI.get(MainActivity.this).isInstall(MainActivity.this,share_media)){
                            LogUtills.LogShow("分享", "未安装相关应用");
                        }
                        setValue("shareUrl", getDataUUIDJson("0",uuidStr));
                        LogUtills.LogShow("分享", share_media.name());
                        LogUtills.LogShow("分享", throwable.getMessage());

                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        setValue("shareUrl", getDataUUIDJson("0",uuidStr));
                    }
                }).open();


    }


    private UMAuthListener authListener = null;
    private static final int UMAUTHCODE = 11101;

    @JavascriptInterface
    public void extLogin(final String platform) { //{"uuid":"e5f37568-904a-438b-9cbc-3addad0cffd8","data":1}

        final String uuidArr[] = getDataUUID(platform);
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("正在读取平台信息...");
        progressDialog.show();
        if (authListener == null) {
            authListener = new UMAuthListener() {
                @Override
                public void onStart(SHARE_MEDIA share_media) {
//                    Toast.makeText(MainActivity.this,"onStart",500);
                }

                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    progressDialog.dismiss();
                    JSONObject successJb = new JSONObject();
                    try {
                        String unionid = map.get("unionid");
                        if (unionid == null || unionid.length() <= 0)
                            unionid = map.get("openid");
                        successJb.put("unionid", unionid);
                        successJb.put("openid", map.get("openid"));
                        successJb.put("nickname", map.get("screen_name"));
                        successJb.put("sex", map.get("gender"));
                        successJb.put("face", map.get("profile_image_url"));
                        successJb.put("city", map.get("city"));
                        successJb.put("province", map.get("province"));
                        successJb.put("accesstoken", map.get("accesstoken"));
                        if (!uuidArr[0].equals("")) {

                            successJb.put("type", Integer.parseInt(uuidArr[0]));
                        }else{
                            successJb.put("type", -1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    LogUtills.LogShow("授权登陆", successJb.toString());
                    if (!uuidArr[0].equals("")) {

                        UMShareAPI.get(MainActivity.this).deleteOauth(MainActivity.this, (Integer.parseInt(uuidArr[0]) == 2 ? SHARE_MEDIA.QQ : SHARE_MEDIA.WEIXIN), null);
                    }else{

                        LogUtils.e("js调用java Native，json中data数据为空");
                    }
                    if (successJb.has("unionid")) {
                        setValue("extLogin", getDataUUIDJson(singleDoubleQuotes(successJb.toString()),uuidArr[1]));
                    } else {
                        setValue("extLogin", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\"}"),uuidArr[1]));
                    }
//                    Toast.makeText(MainActivity.this,"onComplete",500);

                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
//                    Toast.makeText(MainActivity.this,"onError",500);

                    progressDialog.dismiss();
                    if(!UMShareAPI.get(MainActivity.this).isInstall(MainActivity.this,share_media)){
                        LogUtills.LogShow("登录", "未安装相关应用");
                    }
                    setValue("extLogin", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\"}"),uuidArr[1]));
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
//                    Toast.makeText(MainActivity.this,"onCancel",500);
                    progressDialog.dismiss();
                    setValue("extLogin", getDataUUIDJson(singleDoubleQuotes("{\"code\":\"0\"}"),uuidArr[1]));
                }
            };
        }
        UMShareAPI.get(this).getPlatformInfo(MainActivity.this, Integer.parseInt(uuidArr[0]) == 2 ? SHARE_MEDIA.QQ : SHARE_MEDIA.WEIXIN, authListener);
    }


    private PopupWindow window;
    private final int MY_PERMISSIONS_REQUEST_CAMERA_CODE = 4;

    private void showPopupWindow() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.popup_layout, null);
// 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        window = new PopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        window.setBackgroundDrawable(dw);
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(this.getCurrentFocus(),
                Gravity.BOTTOM, 0, 0);

        TextView tv_1 = (TextView) view.findViewById(R.id.first);
        tv_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Android 6.0 需要检查权限 ，对于没有权限的需要先申请权限
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //申请拍照权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA_CODE);
                } else {
                    //拍照
                    takePhotoNoAli();
                }
            }
        });
        TextView tv_2 = (TextView) view.findViewById(R.id.second);
        tv_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //从相册选择
                chosePhoto();
            }
        });
        TextView tv_3 = (TextView) view.findViewById(R.id.thread);
        tv_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取消
                window.dismiss();
            }
        });
    }

    /**
     * 拍照
     */
    private void takePhotoNoAli() {
        window.dismiss();
        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                "lvnong.jpg")));
        startActivityForResult(takeIntent, TAKE_TYPE);
    }

    private final int TAKE_TYPE = 111;
    private final int ALBUM_TYPE = 222;
    private final int CROP_TYPE = 333;

    /**
     * 相册
     */
    private void chosePhoto() {
        window.dismiss();
        Intent albumIntent = new Intent(Intent.ACTION_PICK, null);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, ALBUM_TYPE);
    }

    /**
     * 调用系统的裁剪
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_TYPE);
    }

    private static String path = "/sdcard/myHead/";//sd路径
    private String filePath = "";

    /**
     * 保存图片到sd卡
     */
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "mrkx.jpg";//图片名字
        filePath = fileName;
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 上传头像
     */
    private void uploadPrint(String filePath) {
        HashMap<String, String> params = new HashMap<String, String>();
//        params.put("user_id",userId);
        RequestParams requestParams = new RequestParams();
//        String sendUrl = getUrl(upload_img_url,params);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
        requestParams.addBodyParameter("imgFile", new File(filePath), mime);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST, URL.sendUrl, requestParams, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                Log.d("xx", "success");
                try {
                    JSONObject resultJb = new JSONObject(responseInfo.result.toString());
                    JSONObject sendJb = resultJb.getJSONObject("data");
                    JSONObject r = new JSONObject();
                    r.put("data", sendJb);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Log.d("xx", "error");
            }
        });
    }


    private int mCurrentMaxSize;
    private int mCurrentType;

    /**
     * js上传图片
     */
    @JavascriptInterface
    public void upimg(String s) {
        try {
            uploadImgUrl = "";
            JSONObject jb = new JSONObject(s);
            upLoadImgUrl = jb.getString("data");
            MainApplication.ALiUpLoadToken = upLoadImgUrl;
            //这里初始化阿里云上传图片,传入地址
            ossService = initOSS(endpoint, bucket, upLoadImgUrl);
            imageService = new ImageService(ossService);
            mCurrentType = jb.getInt("multi");
            MainApplication.mUploadType = mCurrentType;
            if (mCurrentType == 1) {
                mCurrentMaxSize = jb.getInt("remain");
                //多张上传
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //申请拍照权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA_CODE);
                } else {
                    //拍照
                    pickImage();
                }
            } else {
                //单张上传

                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //申请拍照权限
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA_CODE);
                } else {
                    //拍照
                    mCurrentMaxSize = 1;
                    pickImage();
                }
            }
        } catch (Exception e) {

        }
    }


    /**
     * js调用原生扫描二维码功能
     */
    @JavascriptInterface
    public void scanf(String s) {
        //Activity中使用
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请拍照权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PhotoChoose.MY_PERMISSIONS_REQUEST_CAMERA_CODE);
        } else {
            startActivity(new Intent(this, CaptureActivity.class));
        }
    }

    /**
     * js调用原生get方法
     */
    @JavascriptInterface
    public void get(String url) {
        //Activity中使用
        String array[] = getDataUUID(url);
        OkHttpUtils.get().url(array[0]).build().execute(new PublicMyStringCallBack() {
            @Override
            public void onResult(String response) {
                setValue("get", response);
            }

            @Override
            public void onError(String message) {
                setValue("get", message);
            }
        });
    }


    /**
     * js调用原生get方法
     */
    @JavascriptInterface
    public void postData(String s) throws Exception {
        //{"url":"http://192.168.1.199:8080/weilai9/api/feedback/save","data":{"phone":11,"customerid":222,"message":"kkkkkkkkkkkk"}}

        JSONObject jb = new JSONObject(getDataUUID(s)[0]);
        String url = jb.getString("url");
        HashMap<String, String> tempParam;
        tempParam = GsonUtils.getInstance().fromJson(jb.getString("data"), new TypeToken<HashMap<String, String>>() {
        }.getType());
        //Activity中使用
        OkHttpUtils.post().url(url)
                .params(tempParam)
                .build()
                .execute(new PublicMyStringCallBack() {
                    @Override
                    public void onResult(String response) {
                        setValue("postData", response);
                    }

                    @Override
                    public void onError(String message) {
                        setValue("postData", message);
                    }
                });
    }


    /**
     * js调用原生
     * 跳转界面
     */
    @JavascriptInterface
    public void go(String url) {
        try {
            openWebActivity = true;
            JSONObject jsonObject = new JSONObject(url);
            String httpAddress = jsonObject.getString("data");
            invokeActivity(this, httpAddress);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否按照微信或者QQ
     *{"data":"{\\\"uuid\\\":\\\"90c76617-351f-4b8c-94ee-8d9c55463642\\\",\\\"data\\\":1,\\\"ext\\\":\\\"true\\\"}","uuid":"90c76617-351f-4b8c-94ee-8d9c55463642"}
     * @param s
     */
    @JavascriptInterface
    public void isExt(String s) {

        if (TextUtils.isEmpty(s)) {

            return;
        }
        try {
            JSONObject jsonObject = new JSONObject();
            String duArr[] = getDataUUID(s);
            if (duArr[0].equals("2")) {
                boolean isQQInstalled = UMShareAPI.get(MainActivity.this).isInstall(MainActivity.this, SHARE_MEDIA.QQ);
                jsonObject.put("ext", isQQInstalled ? true : false);
            } else if (duArr[0].equals("1")) {
                boolean isWeiXinInstalled = UMShareAPI.get(MainActivity.this).isInstall(MainActivity.this, SHARE_MEDIA.WEIXIN);
                jsonObject.put("ext", isWeiXinInstalled ? true : false);
            }
            String tempJson = getDataUUIDJson(singleDoubleQuotes(jsonObject.toString()),duArr[1]);
            setValue("isExt", tempJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private boolean openWebActivity = false;

    /**
     * js调用原生
     * 关闭当前界面
     */
    @JavascriptInterface
    public void close(String s) {
        /*无网络情况下不返回*/
        if(!Utils.isNetworkAvailable(this)){

            ToastUtil.showTop("当前无网络!");
            return ;
        }
        if(!isLoanFinished){

            //当前界面还是加载完成
            ToastUtil.showTop("当前界面还未加载完成!");
            return;
        }
        MyActivityManager.getScreenManager().popActivity(this, loadUrl);

        this.finish();
    }


    @JavascriptInterface
    public void gotop(final String s) {
        try {
            Log.d("size", "" + MyActivityManager.getScreenManager().getASize());
            JSONObject jsonObject = new JSONObject(s);
            final String url = jsonObject.getString("data");
            String uuidStr = jsonObject.getString("uuid");
            if (url.equals("")) {
                //为空
                MainApplication.getInstance().isRefreshHome = false;
                MainApplication.getInstance().isRefreshUrl = url;
                int startPosition = MyActivityManager.stackTagList.indexOf(loadUrl);
                MyActivityManager.getScreenManager().popActivity(startPosition);
            } else {
                final int startPosition = MyActivityManager.getASize() - 1;
                webview.post(new Runnable() {
                    @Override
                    public void run() {
                        if (startPosition > 0) {
                            MainApplication.getInstance().isRefreshHome = true;
                            MainApplication.getInstance().isRefreshUrl = url;
                            MyActivityManager.getScreenManager().popActivity(startPosition);
                        } else {
                            webview.loadUrl(url.indexOf(URL.HTTP_HTTPS) > -1 ? url : (URL.DOMIAN + url));
                        }

                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void getPushToken(String s) {
        try {
            PushAgent mPushAgent = PushAgent.getInstance(this);
            String tokens = mPushAgent.getRegistrationId();
            JSONObject jb = new JSONObject();
            jb.put("type", "友盟");
            jb.put("token", tokens);
            setValue("getPushToken", getDataUUIDJson(singleDoubleQuotes(jb.toString()),getDataUUID(s)[1]));
        } catch (Exception e) {

        }
    }

    /**
     * js调用原生
     * 保存方法,保存到SP
     */
    @JavascriptInterface
    public void storageValue(String s) {
        try {
            JSONObject jb = new JSONObject(getDataUUID(s)[0]);
            String key = jb.getString("key");
            String value = jb.getString("value");
            MySharePreferenceHelper.setString(key, value);
            setValue("storageValue", getDataUUIDJson(value,getDataUUID(s)[1]));
        } catch (Exception e) {
        }
    }

    /**
     * js调用原生
     * 从sp取值,根据key
     */
    @JavascriptInterface
    public void storage(String s) {
        String dataUArr [] = getDataUUID(s);
        String tempStr = MySharePreferenceHelper.PREFERENCES.getString(dataUArr[0], "");
        setValue("storage", getDataUUIDJson(singleDoubleQuotes(tempStr),dataUArr[1]));
    }

    /**
     * js调用原生
     * 获取图片,下载,存本地
     */
    @JavascriptInterface
    public void getImgByUrls(String imgs) {
        if (!TextUtils.isEmpty(imgs)) {
            LoadBase64Img[] loadBase64Img = GsonUtils.getInstance().fromJson(imgs, new TypeToken<LoadBase64Img[]>() {
            }.getType());
            if (loadBase64Img != null) {
                loadBitmaps(loadBase64Img);
            }
        }
    }

    /**
     * js调用原生
     * 设置推送
     */
    @JavascriptInterface
    public void setPush(final String s) {
       final  String open = getDataUUID(s)[0];
       final String uuidStr = getDataUUID(s)[1];
        if (open.equals("get")) {
            String closeStr = MySharePreferenceHelper.PREFERENCES.getString("closePush", "");
            setValue("setPush", (closeStr.equals("1") ? "0" : "1"));
        } else {
            PushAgent push = PushAgent.getInstance(MainActivity.this);
            IUmengCallback pushCb = new IUmengCallback() {
                @Override
                public void onSuccess() {
                    setValue("setPush", getDataUUIDJson("1",uuidStr));
                    MySharePreferenceHelper.setString("closePush", open.equals("1") ? "0" : "1");
                }

                @Override
                public void onFailure(String s, String s1) {
                    setValue("setPush", getDataUUIDJson("0",uuidStr));
                }
            };
            if (Boolean.getBoolean(open)) {
                push.enable(pushCb);
            } else {
                push.disable(pushCb);
            }
        }

    }

    /**
     * js调用原生
     * 获取版本{"uuid":"ca08239b-684f-49cb-9bd4-801d9350bc43"}
     */
    @JavascriptInterface
    public void getVersion(String uuid) {

        try {
            PackageManager pm = MainActivity.this.getPackageManager();
            JSONObject ve = new JSONObject();
            PackageInfo pi = null;
            pi = pm.getPackageInfo(MainActivity.this.getPackageName(), 0);
            ve.put("versionName", pi.versionName);
            ve.put("versionCode", pi.versionCode);
            ve.put("versionType", "android");
            String uuidStr = new JSONObject(uuid).getString("uuid");

            String veJson = singleDoubleQuotes(ve.toString());
            setValue("getVersion", getDataUUIDJson(veJson, uuidStr));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 组装{"data":"xxxxx","uuid":"xxxx"}
     * @param dataStr
     * @param uuidStr {"data":"{\"versionName\":\"2.6\",\"versionCode\":21,\"versionType\":\"android\"}","uuid":"f3869346-ca82-4e44-94ed-2f11154ec053"}
     * @return
     */
    private String getDataUUIDJson(String dataStr, String uuidStr) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("data", dataStr);
            jsonObject.put("uuid", uuidStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return jsonObject.toString();
    }

    /**
     * 对单引号或者双引号做转化
     * @param str
     * @return
     */
    public static String singleDoubleQuotes(String str) {
        str = str == null ? "" : str;
        StringBuffer sb = new StringBuffer(str);
        int i = 0;
        while (i < sb.length()) {
            if (/*sb.charAt(i) == '\'' ||*/ sb.charAt(i) == '\"') {
                sb.insert(i, '\\');
                i += 2;
            } else {
                i++;
            }
        }
        return sb.toString();
    }

    @JavascriptInterface
    public void copyText(String s) {
        try {
            String[] dataUUID =getDataUUID(s);
            JSONObject jb = new JSONObject(dataUUID[0]);
            String ss = jb.getString("text");
            ClipboardManager myClipboard = (ClipboardManager) MainActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData myClip = ClipData.newPlainText("text", ss);
            ToastUtil.showTop("复制成功！");
            myClipboard.setPrimaryClip(myClip);
        } catch (Exception e) {
        }
    }


    @JavascriptInterface
    public void openUrlStr(String url) {
        final Uri uri = Uri.parse(getDataUUID(url)[0]);
        final Intent it = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(it);
    }


    /**
     * 回调js
     *
     * @param method   方法名称
     * @param tempData 回传的数据
     */
    private void setValue(final String method, final String tempData) {
        try {
            webview.post(new Runnable() {
                @Override
                public void run() {
                    webview.loadUrl("javascript:_w9_wcallback('" + tempData + "')");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 回调js
     *
     * @param method 方法名称
     * @param tempId 回传的数据
     */
    private void setValue(final String method, final String tempId, final String tempUrl) {
        try {
            webview.post(new Runnable() {
                @Override
                public void run() {
                    webview.loadUrl("javascript:wcallback('" + method + "','" + tempId + "','" + tempUrl + "')");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 原生上传到js的
     * 定位功能回调
     */
    @Subscribe
    public void onEvent(LocationModel event) {
        setValue("position", GsonUtils.getInstance().toJson(event));
    }

    /**
     * 原生上传到js的
     * scanf功能回调
     */
    @Subscribe
    public void onEvent(final ScanfModel event) {
        setValue("scanf", event.getResutl());
    }


    private static final int REQUEST_CODE = 123;
    private ArrayList<String> mResults = new ArrayList<String>();

    private void chosePhotoForm() {
        Intent intent = new Intent(MainActivity.this, ImagesSelectorActivity.class);
        intent.putExtra(SelectorSettings.SELECTOR_SHOW_CAMERA, true);
        intent.putExtra(SelectorSettings.SELECTOR_MAX_IMAGE_NUMBER, mCurrentMaxSize);
        startActivityForResult(intent, REQUEST_CODE);
    }

    private static final int REQUEST_IMAGE = 211;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    private ArrayList<String> mSelectPath;

    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            uploadPosition = 0;
            MultiImageSelector selector = MultiImageSelector.create();
            selector.showCamera(true);
            selector.count(mCurrentMaxSize);
            selector.start(MainActivity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new android.support.v7.app.AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }


    private Bitmap head;//头像Bitmap
    private final int MY_PERMISSIONS_REQUEST_STORAGE_CODE = 5;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == Activity.RESULT_OK) {
                switch (requestCode) {
                    case REQUEST_IMAGE:
                        if (data == null)
                            return;
                        mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                        MainApplication.mUploadSize = mSelectPath.size();
                        for (int i = 0; i < mSelectPath.size(); i++) {
                            final File file = new File(mSelectPath.get(i));
                            TimerTask task = new TimerTask() {
                                public void run() {
                                    compressImage(file, 720, 1080);
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task, i * 500);
                        }
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setMessage("图片正在上传中...");
                        progressDialog.show();
                        break;
                    case REQUEST_CODE:
                        if (data == null) {
                            return;
                        }
                        mResults = data.getStringArrayListExtra(SelectorSettings.SELECTOR_RESULTS);
                        MainApplication.mUploadSize = mResults.size();
                        for (int i = 0; i < mResults.size(); i++) {
                            File file = new File(mResults.get(i));
                            compressImage(file, 720, 1080);
                        }
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setMessage("图片正在上传中...");
                        progressDialog.show();
                        break;
                    case REQ_CAMERA:
                        //                    if (null == mUploadMessage || mFilePathCallback == null)
                        //                        return;REQ_CAMERAREQ_CHOOSE
                        Uri uri = null;
                        File file = new File(cameraUri.getPath());
                        if (!file.exists()) {
                            cameraUri = Uri.parse("");
                        }
                        afterOpenCamera();
                        uri = cameraUri;
                        if (mFilePathCallback != null) {
                            Uri[] uris = new Uri[1];
                            uris[0] = uri;
                            mFilePathCallback.onReceiveValue(uris);
                        } else {
                            mUploadMessage.onReceiveValue(uri);
                        }
                        mFilePathCallback = null;
                        mUploadMessage = null;
                        break;
                    case REQ_CHOOSE:
                        uri = afterChosePic(data);
                        if (mFilePathCallback != null) {
                            Uri[] uris = new Uri[1];
                            uris[0] = uri;
                            mFilePathCallback.onReceiveValue(uris);
                        } else {
                            mUploadMessage.onReceiveValue(uri);
                        }
                        mFilePathCallback = null;
                        mUploadMessage = null;
                        break;
                    case FILECHOOSER_RESULTCODE:
                        if (null == mUploadMessage) return;
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        if (result != null) {
                            String imagePath = ImageFilePath.getPath(this, result);
                            if (!TextUtils.isEmpty(imagePath)) {
                                result = Uri.parse("file:///" + imagePath);
                            }
                        }
                        mUploadMessage.onReceiveValue(result);
                        mUploadMessage = null;
                        break;
                    case INPUT_FILE_REQUEST_CODE:
                        Uri[] results = null;

                        // Check that the response is a good one
                        if (resultCode == Activity.RESULT_OK) {
                            if (data == null) {
                                // If there is not data, then we may have taken a photo
                                if (mCameraPhotoPath != null) {
                                    //                                Logger.d("camera_photo_path", mCameraPhotoPath);
                                    results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                                }
                            } else {
                                String dataString = data.getDataString();
                                //                            Logger.d("camera_dataString", dataString);
                                if (dataString != null) {
                                    results = new Uri[]{Uri.parse(dataString)};
                                }
                            }
                        }

                        mFilePathCallback.onReceiveValue(results);
                        mFilePathCallback = null;
                        break;
                    case TAKE_TYPE:
                        if (resultCode == -1) {
                            File temp = new File(Environment.getExternalStorageDirectory()
                                    + "/mrkx.jpg");
                            cropPhoto(Uri.fromFile(temp));//裁剪图片
                        }
                        break;
                    case ALBUM_TYPE:
                        if (resultCode == -1) {
                            cropPhoto(data.getData());//裁剪图片
                        }
                        break;
                    case CROP_TYPE:
                        if (data != null) {
                            Bundle extras = data.getExtras();
                            head = extras.getParcelable("data");
                            if (head != null) {
                                /**
                                 * 上传服务器代码
                                 *  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
                                 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
                                 */
                                //Android 6.0 需要检查权限 ，对于没有权限的需要先申请权限
                                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                    //申请拍照权限
                                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_STORAGE_CODE);
                                } else {
                                    setPicToView(head);//保存在SD卡中
                                }
                                uploadPrint(filePath);
                            }
                        }
                        break;
                    case 10001:
                        double latitude = data.getDoubleExtra("latitude", 0);
                        double longitude = data.getDoubleExtra("longitude", 0);
                        String locationAddress = data.getStringExtra("address");
                        String locationName = data.getStringExtra("name");
                        String str = "latitude: " + latitude + "\n" + "longitude: " + longitude + "\n" +
                                "locationAddress: " + locationAddress + "\n" +
                                "locationName: " + locationName;
                        Log.d("zb", str);
                        String sheng = data.getStringExtra("sheng");
                        String shi = data.getStringExtra("shi");
                        String qu = data.getStringExtra("qu");
                        LocationModel event = new LocationModel();
                        event.setLat(latitude);
                        event.setLng(longitude);
                        event.setProvince(sheng);
                        event.setCity(shi);
                        event.setRegion(qu);
                        event.setAddress(locationAddress);
                        setValue("selectPosition", GsonUtils.getInstance().toJson(event));
                        break;
                    case PhotoChoose.TAKE_TYPE://拍照返回
                        if (resultCode == RESULT_OK) {
                            progressDialog = new ProgressDialog(MainActivity.this);
                            progressDialog.setMessage("图片正在上传中...");
                            progressDialog.show();
                            takeCamera();
                        }
                        break;
                    case PhotoChoose.ALBUM_TYPE://相册选择返回
                        final Intent finalData = data;
                        if (resultCode == RESULT_OK) {
                            new Runnable() {
                                @Override
                                public void run() {
                                    progressDialog = new ProgressDialog(MainActivity.this);
                                    progressDialog.setMessage("图片正在上传中...");
                                    progressDialog.show();
                                    choosePhoto(finalData);
                                }
                            }.run();
                        }
                        break;
                    case UMAUTHCODE://友盟回调
                        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
                        if(progressDialog!=null)
                            progressDialog.dismiss();
                        break;
                }
            } else {
                if (requestCode == REQ_CAMERA || requestCode == REQ_CHOOSE) {
                    if (mFilePathCallback != null) {
                        Uri[] uris = new Uri[1];
                        uris[0] = Uri.parse("");
                        mFilePathCallback.onReceiveValue(uris);
                        mFilePathCallback = null;
                    } else {
                        mUploadMessage.onReceiveValue(Uri.parse(""));
                        mUploadMessage = null;
                    }
                }
            }
        } catch (Exception e) {
            try {
                if (progressDialog != null)
                    progressDialog.dismiss();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }


    /**
     * 上传图片到服务器(阿里云)
     *
     * @param firl
     */
    private void upload(final File firl) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        uploadAliImg(str + "/" + firl.getName(), firl.getAbsolutePath());

    }



/*
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }*/


    /*************************************
     * 权限申请
     ****************************************************/
    private String permissionInfo;
    private final int SDK_PERMISSION_REQUEST = 127;

    @Override
    public void onUnreadCountChange(final int count) {
        LogUtills.LogShow("onUnreadCountChange", "" + count);
        if (count > 0) {
            //通知js更新页面
            try {
                webview.post(new Runnable() {
                    @Override
                    public void run() {
                        LogUtills.LogShow("onUnreadCountChange", "正在回调js:_w9_reActive");
                        webview.loadUrl("javascript:_w9_reActive('" + count + "')");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void qiyuUrlOnclicker(Context context, String url) {

    }


    /*********************************************
     * 照片处理
     ******************************************************************/
    class UserChoseImageHeadActivity extends PopupWindow implements
            View.OnClickListener {

        private Context context;
        private TextView mChoseBtn;
        private TextView mCameraImg;
        private TextView mCanelTxt;
        private View mPop;

        public UserChoseImageHeadActivity(Context context) {
            this.context = context;
            LayoutInflater inflatr = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mPop = inflatr.inflate(R.layout.pop_window_upload_camera_img, null);
            mChoseBtn = (TextView) mPop.findViewById(R.id.user_chose_album);
            mCameraImg = (TextView) mPop.findViewById(R.id.user_camera_img);
            mCanelTxt = (TextView) mPop.findViewById(R.id.user_info_canel);

            mChoseBtn.setOnClickListener(this);
            mCameraImg.setOnClickListener(this);
            mCanelTxt.setOnClickListener(this);

            this.setContentView(mPop);
            this.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
            this.setHeight(ActionBar.LayoutParams.MATCH_PARENT);
            this.setFocusable(true);

            ColorDrawable dw = new ColorDrawable(0xb0000000);
            this.setBackgroundDrawable(dw);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_chose_album://相册
                    // 相册选取
                    Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, PhotoChoose.ALBUM_TYPE);
                    UserChoseImageHeadActivity.this.dismiss();
                    break;
                case R.id.user_camera_img://拍照
                    takePhoto();
                    UserChoseImageHeadActivity.this.dismiss();
                    break;
                case R.id.user_info_canel:
                    UserChoseImageHeadActivity.this.dismiss();
                    break;
            }
        }

    }


    /**
     * 拍照存贮图片路径
     */
    String imageFilePath = "";

    /**
     * 用来压缩的图片文件,拍照用
     */
    File imageCameraFile = null;

    /**
     * 拍照
     */
    private void takePhoto() {
        //拍照
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请拍照权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PhotoChoose.MY_PERMISSIONS_REQUEST_CAMERA_CODE);
        } else {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
                String out_file_path = SDcardHelper.PATH;
                File dir = new File(out_file_path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                imageFilePath = SDcardHelper.PATH + System.currentTimeMillis() + PhotoChoose.headName;
                imageCameraFile = new File(imageFilePath);
                getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageCameraFile));
                getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(getImageByCamera, PhotoChoose.TAKE_TYPE);
            } else {
                ToastUtil.showTop("请确认已经插入SD卡");
            }

        }

    }


    /**
     * 处理拍照上传
     */
    private void takeCamera() {
        try {
            if (imageCameraFile != null) {
                compressImage(imageCameraFile, 720, 1080);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理从相册选择的
     *
     * @param data
     */
    private void choosePhoto(Intent data) {
        Bitmap bm = null;
        // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
        ContentResolver resolver = getContentResolver();
        try {
            Uri originalUri = data.getData(); // 获得图片的uri
            bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片
            takeUpLoad(bm);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @param bm 根据bm确认图片是否需要裁剪,然后压缩
     */
    private void takeUpLoad(Bitmap bm) {
        if (bm != null) {
            if (bm.getWidth() > 960) {
                float xx = ((bm.getWidth() * 1.0f) / 960 * 1.0f);
                int hh = (int) ((bm.getHeight() * 1.0f) / xx);
                File file = SDcardHelper.getUploadFile(bm);
                compressImage(file, 960, hh);
            } else {
                File file = SDcardHelper.getUploadFile(bm);
                compressImage(file, bm.getWidth(), bm.getHeight());
            }
        }
    }


    /**
     * 图片压缩
     *
     * @param mFile 需要压缩的文件
     * @param width 目标文件宽
     * @param height 目标文件高
     */
    ProgressDialog progressDialog;

    private void compressImage(File mFile, int width, int height) {
        try {
            Luban.get(this).load(mFile).setMaxSize(500).setMaxHeight(height).setMaxWidth(width)
                    .putGear(Luban.THIRD_GEAR)
                    .launch(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            Log.e("压缩:", "start");
                        }

                        @Override
                        public void onSuccess(File file) {
                            Log.e("压缩:", "Success");
                            upload(file);
                        }

                        @Override
                        public void onError(Throwable e) {
                            progressDialog.dismiss();
                            Log.e("压缩:", "onError");
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化阿里云上传
     *
     * @param imgUrl   服务器地址
     * @param endpoint
     * @param bucket
     * @return
     */
    public OssService initOSS(String endpoint, String bucket, String imgUrl) {
        //如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        //OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        credentialProvider = new STSGetter(imgUrl);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(this, endpoint, credentialProvider, conf);
        return new OssService(oss, bucket);

    }

    /**
     * 上传到阿里云
     *
     * @param name
     * @param filePate
     */
    private void uploadAliImg(String name, String filePate) {
        task = new WeakReference<>(ossService.asyncMultiPartUpload(name, filePate, null));
    }

    String uploadImgUrl = "";
    int uploadPosition = 0;

    /**
     * @param event 上传图片到阿里云的返回
     */
    @Subscribe
    public void onEvent(String event) {
        if (event.equals("success")) {
            try {
                JSONObject jb = new JSONObject();
                jb.put("code", 1);
                jb.put("msg", "");
                setValue("pay", jb.toString());
            } catch (Exception e) {
            }
        } else if (event.equals("error")) {
            try {
                JSONObject jb = new JSONObject();
                jb.put("code", 0);
                jb.put("msg", "支付失败");
                setValue("pay", jb.toString());
            } catch (Exception e) {
            }
        } else {
            if (event.equals("uploaderror")) {
                setValue("upimg", "");
                ToastUtil.showTop("上传图片失败");
            } else {
                if (!uploadImgUrl.contains(event)) {
                    uploadPosition++;
                    uploadImgUrl = uploadImgUrl + event + ",";
                }
                if (uploadPosition == MainApplication.mUploadSize) {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    setValue("upimg", uploadImgUrl);
                    uploadPosition = 0;
                    uploadImgUrl = "";
                }
            }
        }

    }


    /********************************下载图片相关***************************************/
    /**
     * 记录所有正在下载或等待下载的任务。
     */
    private Set<BitmapWorkerTask> taskCollection;

    /**
     * 需要下载的对象集合
     */
    LoadBase64Img[] tempLoad = null;

    /**
     * @param infos 加载
     */
    private void loadBitmaps(LoadBase64Img[] infos) {
        //获取数据库
        databaseUtil = new DatabaseUtil(MainActivity.this);
        tempLoad = infos;
        taskCollection = new HashSet<BitmapWorkerTask>();
        try {
            int allsize = 0;
            while (allsize < infos.length) {
                LoadBase64Img loadBase64Img = infos[allsize];
                List<SaveImg> listObjet = databaseUtil.queryByname(loadBase64Img.getUrl());
                if (listObjet != null && listObjet.size() > 0) {
                    setValue("getImgByUrls", loadBase64Img.getId(), listObjet.get(0).getUrldate());
                } else {
                    BitmapWorkerTask task = new BitmapWorkerTask();
                    taskCollection.add(task);
                    task.execute(loadBase64Img.getUrl());
                }
                allsize++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 取消所有正在下载或等待下载的任务。
     */
    public void cancelAllTasks() {
        if (taskCollection != null) {
            for (BitmapWorkerTask task : taskCollection) {
                task.cancel(false);
            }
        }
    }


    /**
     * 异步下载图片的任务。
     *
     * @author guolin
     */
    class BitmapWorkerTask extends AsyncTask<String, Void, String> {

        /**
         * 图片的URL地址
         */
        private String imageUrl;

        @Override
        protected String doInBackground(String... params) {
            imageUrl = params[0];
            // 在后台开始下载图片
            String bitmap = downloadBitmap(params[0]);
            if (bitmap != null) {
                // 图片下载完成后缓存到LrcCache中
//                addBitmapToMemoryCache(params[0], bitmap);
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(String bitmap) {
            super.onPostExecute(bitmap);
            if (!TextUtils.isEmpty(bitmap)) {
                String key = getLoadkey(imageUrl);
                setValue("getImgByUrls", key, bitmap);
                insertInfo(imageUrl, bitmap);
            } else {
                ToastUtil.showTop("下载失败");
            }
            taskCollection.remove(this);
        }

        /**
         * 建立HTTP请求，并获取Bitmap对象。
         *
         * @param imageUrl 图片的URL地址
         * @return 解析后的Bitmap对象
         */
        private String downloadBitmap(String imageUrl) {
            String imgStr = "";
            HttpClient httpClient = new DefaultHttpClient();
            InputStream inputStream = null;
            try {
                HttpGet httpGet = new HttpGet(imageUrl);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    inputStream = httpResponse.getEntity().getContent();
                    imgStr = castBase64(inputStream);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return imgStr;
        }
    }


    /**
     * 插入到数据库
     *
     * @param imageUrl
     * @param bitmap
     */
    private void insertInfo(String imageUrl, String bitmap) {
        SaveImg saveInfo = new SaveImg();
        saveInfo.setUrl(imageUrl);
        saveInfo.setUrlsize(bitmap.length());
        saveInfo.setUrltime(System.currentTimeMillis());
        saveInfo.setUrldate(bitmap);
        databaseUtil.Insert(saveInfo);
    }

    /**
     * @param url
     * @return 通过url获取回调的key
     */
    private String getLoadkey(String url) {
        if (tempLoad != null && tempLoad.length > 0) {
            for (int i = 0; i < tempLoad.length; i++) {
                if (url.equals(tempLoad[i].getUrl())) {
                    return tempLoad[i].getId();
                }
            }
        }
        return "";
    }


    /**
     * @param inputStream
     * @return 返回图片的base64地址
     */
    private String castBase64(InputStream inputStream) {
        String tempStr = "";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            byte[] bs = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            byte b[] = bos.toByteArray();
            tempStr = Base64.encodeToString(b, Base64.DEFAULT);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tempStr;
    }


    /**
     * //弹出确认dialog，包含确定，取消按钮
     *
     * @param mess
     */
    private void showConfirm(String mess) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getDataUUID(mess)[0]);
        builder.setCancelable(false);
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setValue("confirm", "1");
                dialog.cancel();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setValue("confirm", "0");
                dialog.cancel();
            }
        });
        builder.create().show();
    }


    /**
     * //弹出对话框架dialog，包含提示内容，确定按钮
     *
     * @param mess
     */
    private void showAlert(String mess) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getDataUUID(mess)[0]);
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setValue("alert", "1");
                dialog.cancel();
            }
        });
        builder.create().show();
    }

    /**
     * 打开，客服{"uuid":"ea96b3db-5485-4d3a-9256-0ee9537ed722","data":{"login":0}}
     */
    @JavascriptInterface
    public void qiyu(String objStr) {
        try {
            String array[] = getDataUUID(objStr);
            LogUtills.LogShow("商品超链接",objStr);
            JSONObject jb = new JSONObject(array[0]);
            if (!jb.has("login") || jb.getInt("login") == 0) {
                //注销用户
                Unicorn.logout();
            } else {
                //打开客服窗口
                //如果用户存在展示用户信息
                LogUtills.LogShow("goods",jb.has("goods")?jb.getJSONObject("goods").getString("url"):"");
                if (jb.has("user")) {
                    JSONObject user = jb.getJSONObject("user");
                    YSFUserInfo userInfo = new YSFUserInfo();
                    userInfo.userId = user.getString("userId");
                    userInfo.authToken = "";
                    userInfo.data = "[\n" +
                            "    {\"key\":\"real_name\", \"value\":\"" + user.getString("real_name") + "\"},\n" +
                            "    {\"key\":\"mobile_phone\", \"value\":\"" + user.getString("mobile_phone") + "\"},\n" +
                            "    {\"key\":\"avatar\", \"value\": \"" + user.getString("avatar") + "\"},\n" +
                            "]";
                    Unicorn.setUserInfo(userInfo);
                    DemoCache.ysfOptions.uiCustomization.rightAvatar=user.getString("avatar");
                    DemoCache.ysfOptions.onMessageItemClickListener = new OnMessageItemClickListener() {
                        @Override
                        public void onURLClicked(Context context, String url) {
                            LogUtills.LogShow("点击商品链接",url);
                            invokeActivity(context, url);
                        }
                    };
                }
                consultService(jb);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void consultService(JSONObject jb) throws JSONException {
        ConsultSource source = new ConsultSource("", "", "");
        if (jb != null && jb.has("goods")) {
            JSONObject goods = jb.getJSONObject("goods");
            ProductDetail.Builder gb = new ProductDetail.Builder();
            gb.setTitle(goods.getString("title"));
            gb.setPicture(goods.getString("picture"));
            gb.setDesc(goods.getString("desc"));
            gb.setNote(goods.getString("note"));
            gb.setUrl(goods.getString("url"));
            gb.setShow(1);
            gb.setAlwaysSend(true);
            source.productDetail = gb.create();
        }
        addUnreadCountChangeListener(true);
        Unicorn.openServiceActivity(MainActivity.this, "候鸟洋货仓客服", source);
    }

    /**
     * 分解
     * @param s
     * @return
     */
    public String[] getDataUUID(String s) {

        String[] du = new String[2];
        try {
            JSONObject jsonObject = new JSONObject(s);

            du[0] = jsonObject.has("data") ? jsonObject.getString("data") : "";
            du[1] = jsonObject.getString("uuid");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return du;
    }

    @JavascriptInterface
    public void isWiFi(String s) {

        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            setValue("isWiFi", getDataUUIDJson("1",getDataUUID(s)[1]));// "isWiFi","1"
        } else {
            setValue("isWiFi", getDataUUIDJson("0",getDataUUID(s)[1]));
        }
    }

    @JavascriptInterface
    public void clearCache(String s) {
        try {
            File[] ff1 = MainApplication.getInstance().getFilesDir().getParentFile().getAbsoluteFile().listFiles();
            deleteFiles(ff1);
            Unicorn.clearCache();
            setValue("clearCache", getDataUUIDJson("1",getDataUUID(s)[1]));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void deleteFiles(File[] ff) {
        if (ff.length > 0) {
            for (int i = 0; i < ff.length; i++) {
                if (!ff[i].isDirectory()) {
                    String pp = ff[i].getPath();
                    //LogUtills.LogShow("pp:",pp);
                    String webviewcc = pp.toLowerCase();
                    if (webviewcc.contains("webview") && webviewcc.contains("cache")) {
                        File deleteFile = ff[i];
                        if (deleteFile.exists()) {
                            Log.e("pp:", webviewcc);
                            deleteFile.delete();
                        }
                    }
                } else {
                    File[] temp = ff[i].listFiles();
                    deleteFiles(temp);
                }
            }
        }
    }
}
